﻿using System;
using System.Collections.Generic;

using System.Linq;
using System.Text;
using System.Web;

using Microsoft.SharePoint.WebControls;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Administration;
using System.Web.UI.WebControls;
using System.Data;
using System.Reflection;
using zevenseas.LifeCycleManagement.Utilities;
using zevenseas.LifeCycleManagement.TimerJobs;

namespace zevenseas.LifeCycleManagement.ApplicationPages
{
    public class OverviewSites : Microsoft.SharePoint.WebControls.LayoutsPageBase
    {
        protected ToolBarButton Mail;
        protected ToolBarButton Lock;
        protected ToolBarButton Delete;
        protected InputFormTextBox TxtUrlSearch;
        protected Label JobStatus;
        protected WebApplicationSelector Selector;
        protected SPGridView gridView;

        private ObjectDataSource dataSource;
        private DataView dataView;      

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (!Utilities.Utilities.IsEmailConfigured())
            {
                Mail.Visible = false;
            }
        }

        protected override void OnLoadComplete(EventArgs e)
        {
            try
            {
                SPWebApplication webApplication = Selector.CurrentItem;
                

                SiteLifeCycleGatherTimerjob gatherJob = webApplication.JobDefinitions.GetValue<SiteLifeCycleGatherTimerjob>("LCMGatherJob_Manual");
                if (gatherJob != null)
                {
                    this.JobStatus.Text = "Statistics Gathering Timer Job is running and processed " + gatherJob.PSitesProcessed.ToString() + " sites so far"; ;
                }
                else
                {
                    this.JobStatus.Text = "Statistics Gathering Timer Job is not running";
                    GatherTimerJobStatus status = webApplication.GetChild<GatherTimerJobStatus>("GatherTimerJobStatus");
                    if (status != null)
                    {
                        this.JobStatus.Text += "<BR>Statistics Gathering Timer Job last ran at " + status.LastRunTime.ToShortDateString();
                    }
                }

                SiteLifeCycleActionTimerjob actionJob = webApplication.JobDefinitions.GetValue<SiteLifeCycleActionTimerjob>("LCMActionJob_Manual");
                if (actionJob != null)
                {
                    this.JobStatus.Text += "<BR>Maintenance Timer Job is not running is running and processed " + actionJob.PSitesProcessed.ToString() + " sites so far"; ;
                }
                else
                {
                    this.JobStatus.Text += "<BR>Maintenance Timer Job is not running at the moment";
                    ActionTimerJobStatus status = webApplication.GetChild<ActionTimerJobStatus>("ActionTimerJobStatus");
                    if (status != null)
                    {
                        this.JobStatus.Text += "<BR>Maintenance Timer Job last ran at " + status.LastRunTime.ToShortDateString();
                    }
                }

            }
            catch
            {
            }
            base.OnLoadComplete(e);
        }

        public DataTable GetSites()
        {
            DataTable sitesDataTable = new DataTable();
           
            if (Utilities.Utilities.CheckIfLCMExists())
            {
                SPList unusedSitesList = SPContext.Current.Web.Webs["LCM"].Lists["UnusedSites"];

                SPQuery query = new SPQuery();
                //query.Query = "<Where><Eq><FieldRef Name='WebApplication' /><Value Type='Text'>" + Selector.CurrentName + "</Value></Eq></Where><OrderBy />";
                query.Query = "<OrderBy><FieldRef Name='ID' Ascending='True' /></OrderBy>";
                sitesDataTable = unusedSitesList.GetItems(query).GetDataTable();
                
            }

            return sitesDataTable;           
        }

        public void RefreshStatsClick(object sender, EventArgs e)
        { 
        
        }

        public void SearchLinkClick(object sender, EventArgs e)
        {
        }

        public void GatherLink(object sender, EventArgs e)
        {
            SPWebApplication local = Selector.CurrentItem;
            if (local.JobDefinitions.GetValue<SiteLifeCycleGatherTimerjob>("LCMGatherJob_Manual") == null)
            {
                SiteLifeCycleGatherTimerjob siteLifeCycleGatherJob = new SiteLifeCycleGatherTimerjob("LCMGatherJob_Manual", local, null, SPJobLockType.Job);
                SPOneTimeSchedule schedule = new SPOneTimeSchedule(DateTime.Now);
                siteLifeCycleGatherJob.Schedule = schedule;
                siteLifeCycleGatherJob.Name = "LCMGatherJob_Manual";
                siteLifeCycleGatherJob.Title = "LCMGatherJob_Manual";                
                siteLifeCycleGatherJob.Update();                
            }
        }

        public void ActionLink(object sender, EventArgs e)
        {
            SPWebApplication local = Selector.CurrentItem;
            if (local.JobDefinitions.GetValue<SiteLifeCycleGatherTimerjob>("LCMActionJob_Manual") == null)
            {
                SiteLifeCycleActionTimerjob siteLifeCycleActionTimerjob = new SiteLifeCycleActionTimerjob("LCMActionJob_Manual", local, null, SPJobLockType.Job);
                SPOneTimeSchedule schedule = new SPOneTimeSchedule(DateTime.Now);
                siteLifeCycleActionTimerjob.Schedule = schedule;
                siteLifeCycleActionTimerjob.Name = "LCMActionJob_Manual";
                siteLifeCycleActionTimerjob.Title = "LCMActionJob_Manual";
                siteLifeCycleActionTimerjob.Update();
            }
        }

        public void LockLink(object sender, EventArgs e)
        {
            if (((base.Request != null) && (base.Request["ctl00$PlaceHolderMain$HiddenSiteSelections"] != null)) && !string.IsNullOrEmpty(base.Request["ctl00$PlaceHolderMain$HiddenSiteSelections"]))
            {
                string[] urls = base.Request["ctl00$PlaceHolderMain$HiddenSiteSelections"].ToString().Split(new Char[] { '#' });

                foreach (string url in urls)
                {
                    if (!string.IsNullOrEmpty(url))
                    {
                        bool locked = false;
                        try
                        {
                            SPSiteAdministration siteAdmin = new SPSiteAdministration(url);
                            siteAdmin.WriteLocked = true;
                            siteAdmin.Dispose();
                            locked = true;
                        }
                        catch (Exception error)
                        {
                            SPUtility.TransferToErrorPage(error.Message.ToString());
                        }

                        if (locked)
                        {
                            SPListItem item = Utilities.Utilities.GetAssociatedListItem(url);
                            item["Locked"] = true;
                            item["LockedAt"] = System.DateTime.Today;
                            item.Update();
                        }
                    }
                }
            }           
        }

        public void MailLink(object sender, EventArgs e)
        {
            if (((base.Request != null) && (base.Request["ctl00$PlaceHolderMain$HiddenSiteSelections"] != null)) && !string.IsNullOrEmpty(base.Request["ctl00$PlaceHolderMain$HiddenSiteSelections"]))
            {
                string[] urls = base.Request["ctl00$PlaceHolderMain$HiddenSiteSelections"].ToString().Split(new Char[] { '#' });

                foreach (string url in urls)
                {
                    if (!string.IsNullOrEmpty(url))
                    {
                        SPListItem item = Utilities.Utilities.GetAssociatedListItem(url);
                        SPWebApplication webApplication = Selector.CurrentItem;
                        SiteLifeCycleSettings settings = webApplication.GetChild<SiteLifeCycleSettings>("SiteLifeCycleSettings");
                        
                        string emailBody = string.Empty;
                        string emailSubject = string.Empty;

                        if (settings != null)
                        {  
                            emailBody = settings.emailBody.ToString();
                            emailSubject = settings.emailSubject.ToString();
                        }

                        string emailTo = item["OwnerEmailAddress"].ToString();
                        ////string emailSubject = item["Title"] + " at : " + url + Utilities.Utilities.GetWebProperty("mailSubject", SPContext.Current.Web.Properties);
                        ////string emailBody = Utilities.Utilities.GetWebProperty("mailContent", SPContext.Current.Web.Properties);

                        if (SPUtility.SendEmail(item.ParentList.ParentWeb, false, false, emailTo, emailSubject, emailBody))
                        {
                            //updating list if email is successfully sent
                            item["MailedAt"] = System.DateTime.Today;
                            item["Mailed"] = true;
                            item.Update();
                        }
                    }
                }
            }
        }

        public void DeleteLink(object sender, EventArgs e)
        {
            if (((base.Request != null) && (base.Request["ctl00$PlaceHolderMain$HiddenSiteSelections"] != null)) && !string.IsNullOrEmpty(base.Request["ctl00$PlaceHolderMain$HiddenSiteSelections"]))
            {
                string[] urls = base.Request["ctl00$PlaceHolderMain$HiddenSiteSelections"].ToString().Split(new Char[] { '#' });

                foreach (string url in urls)
                {
                    if (!string.IsNullOrEmpty(url))
                    {
                        bool siteIsDeleted = false;

                        try
                        {
                            SPSiteAdministration siteAdmin = new SPSiteAdministration(url);
                            siteAdmin.Delete();
                            siteAdmin.Dispose();
                            siteIsDeleted = true;
                        }

                        catch (Exception error)
                        {
                            SPUtility.TransferToErrorPage(error.Message.ToString());
                        }

                        if (siteIsDeleted)
                        {
                            SPListItem item = Utilities.Utilities.GetAssociatedListItem(url);
                            item["Deleted"] = true;
                            item["DeletedAt"] = System.DateTime.Today;
                            item.Update();

                        }
                    }
                }
            }
        }
    }
}
